﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Debug;
using System;
using System.Collections.Generic;
using System.Text;

namespace hoemwork
{
    class SqlDbContext : DbContext
    {
        // 按继承映射：Problem/Article/Suggest以及他们的父类Content

        public DbSet<Student> Students { get; set; }
        public DbSet<User> Users { get; set; }
        //public DbSet<Email> Emails { get; set; }
        //public DbSet<Problem> Problems { get; set; }
        //public DbSet<Article> Articles { get; set; }
        //public DbSet<Content> Contents { get; set; }
        //public DbSet<Suggest> Suggests { get; set; }
        //public DbSet<Message> Messages { get; set; }
        public DbSet<Teacher> Teachers { get; set; }
        public DbSet<Person> Persons { get; set; }
        public DbSet<Classroom> Classrooms { get; set; }
        public DbSet<BangMoney> BangMoneys { get; set; }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            string connStr =
                @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=17bang;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
            optionsBuilder
                .UseSqlServer(connStr)
               // .UseLazyLoadingProxies()

#if DEBUG
                .EnableSensitiveDataLogging()

#endif
                .LogTo(
                (id, level) => true //level == LogLevel.Debug,//过滤条件
                ,log => Console.WriteLine(log)//如何记录log
                );
            base.OnConfiguring(optionsBuilder);
        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Student>().HasBaseType((Type)null);
            modelBuilder.Entity<Teacher>().HasBaseType((Type)null);
            modelBuilder.Entity<User>().HasBaseType((Type)null);
            //modelBuilder.Entity<Email>().HasBaseType((Type)null);
            //modelBuilder.Entity<Problem>().HasBaseType((Type)null);
            //modelBuilder.Entity<Article>().HasBaseType((Type)null);
            //modelBuilder.Entity<Content>().HasBaseType((Type)null);
            //modelBuilder.Entity<Suggest>().HasBaseType((Type)null);
            modelBuilder.Entity<Student>()
                .HasOne<Bed>(s => s.SleepIn)
                .WithOne(b => b.Owner)
                .HasForeignKey<Student>(s => s.SleepInId)
                .OnDelete(DeleteBehavior.Cascade )
                ;
            modelBuilder.Entity<Student>(opt =>
            {
                opt.Property<DateTime>("EnrollDate");
            });
            modelBuilder.Entity<Teacher>()
                .HasCheckConstraint("CK_Salary","Salary>=0");
                

            modelBuilder.Entity<User>()
                  .HasOne<Email>(u => u.EmailIn)
                  .WithOne(e => e.User)
                  .HasForeignKey<Email>(e => e.UserId);
            modelBuilder.Entity<BangMoney>()
                .HasCheckConstraint("CK_BMoney", "BMoney>=0");


            //modelBuilder.Entity<Student>().ToTable("Students");
            //modelBuilder.Entity<Teacher>().ToTable("Teachers");//Table-Per-Type策略（TPT）EF core 5.0开始支持


            // 将User的主键改回为Id
            modelBuilder.Entity<User>(u =>
            {

                u.Ignore(u => u.FailedTry);
                u.HasKey(u => u.id);
                u.HasIndex(u => u.CreateTime).IsUnique();
                u.HasCheckConstraint("CK_CreateTime", "CreateTime >= '2020-01-01'");
            });
            //modelBuilder.Entity<Problem>(p =>
            //{
            //    p.HasKey(p => p.Id);
            //});
            //modelBuilder.Entity<Message>(m =>
            //{
            //    m.HasKey(m => m.Id);
            //});
            modelBuilder.Entity<Email>(e =>
            {
                e.HasKey(e => e.Id);
            });

            base.OnModelCreating(modelBuilder);
        }

    }

}
